package org.apache.ocean.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ZipUtils {

	public byte[] unzip(byte[] compressedData) {
		// Create the decompressor and give it the data to compress
		Inflater decompressor = new Inflater();
		decompressor.setInput(compressedData);
		// Create an expandable byte array to hold the decompressed data
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(compressedData.length);
		// Decompress the data
		byte[] buffer = new byte[1024];
		while (!decompressor.finished()) {
			try {
				int count = decompressor.inflate(buffer);
				byteArrayOutputStream.write(buffer, 0, count);
			} catch (DataFormatException e) {
			}
		}
		try {
			byteArrayOutputStream.close();
		} catch (IOException e) {
		}
		// Get the decompressed data
		byte[] decompressedData = byteArrayOutputStream.toByteArray();
		return decompressedData;
	}

	public static byte[] zip(byte[] inputBytes) throws Exception {
		Deflater compressor = new Deflater();
		compressor.setLevel(Deflater.BEST_SPEED);
		// Give the compressor the data to compress
		compressor.setInput(inputBytes);
		compressor.finish();
		// Create an expandable byte array to hold the compressed data.
		// You cannot use an array that's the same size as the orginal because
		// there is no guarantee that the compressed data will be smaller than
		// the uncompressed data.
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(inputBytes.length);
		// Compress the data
		byte[] buffer = new byte[1024];
		while (!compressor.finished()) {
			int count = compressor.deflate(buffer);
			byteArrayOutputStream.write(buffer, 0, count);
		}
		try {
			byteArrayOutputStream.close();
		} catch (IOException e) {
		}
		// Get the compressed data
		byte[] compressedData = byteArrayOutputStream.toByteArray();
		return compressedData;
	}
}
